﻿using System;
using System.Runtime.Remoting.Messaging;
using System.Text.RegularExpressions;

namespace SkyCli.OAuth
{
    /// <summary>
    /// Interaction logic for OAuth.xaml
    /// </summary>
    public partial class OAuthConsent
    {
        private const string SignInUrl =
            "https://login.live.com/oauth20_authorize.srf?client_id={0}&scope=wl.skydrive,wl.offline_access&response_type=code&redirect_uri=https://login.live.com/oauth20_desktop.srf";


        public OAuthConsent(string clientId)
        {
            InitializeComponent();
            webBrowser.Navigate(new Uri(string.Format(SignInUrl, clientId)));
        }

        private void WebBrowserLoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.Query.Contains("code="))
            {
                var respParams = Regex.Split(e.Uri.Query.Remove(0, 1), "&");
                foreach (var param in respParams)
                {
                    var nvPair = Regex.Split(param, "=");
                    if (nvPair[0]=="code")
                        CallContext.SetData("skycli_auth_code", nvPair[1]); 
                }
                Close();
            }
        }    
    }
}
